# -*- coding: utf-8 -*-
# -文件说明 图片下载和存储-
# @Time    : 2019/8/8 16:38
# @Author  : hwx
# @Email   : @163.com
# @File    : 爬虫demo3_图片下载.py
# @Software: PyCharm
import requests
import os


def getHTMLText(url):
    try:
        r = requests.get(url)  # 请用get，用post出错
        print('状态码：' + str(r.status_code))
        print(r.request.url)
        r.raise_for_status()  # 如果不是200，抛出异常
        r.encoding = 'utf-8'
        return r
    except BaseException:
        return "getHTMLText产生异常"


url = 'http://img0.dili360.com/pic/2019/03/07/5c80bb870ebb81134492900_t.jpg@!rw9'[:- 5]

# http://img0.dili360.com/pic/2019/03/07/5c80bb7e9f35c6x97078433_t.jpg@!rw9
# http://img0.dili360.com/ga/M00/47/EF/wKgBzFlDQnWAU5dKACd7TLyocKo220.tub.jpg@!rw9
root = 'D://hwx//python//PythonLearning//'
path = root + url.split('/')[-1]
print(path)
print('开始爬取图片')
if not os.path.exists(root):
    os.mkdir(root)
if not os.path.exists(path):
    r = getHTMLText(url)
    with open(path, 'wb') as f:
        f.write(r.content)
        f.close()
        print('文件保存成功')
else:
    print('文件已存在')
